import React, { useState, useEffect, useContext } from 'react';
import {
    Tag, message, Button, Layout, Menu, Avatar, Dropdown, Space, Modal, Form, Input, Radio, Tabs, Empty, Collapse, Descriptions, Card, Flex, Pagination
} from 'antd';
const { Header, Sider, Content } = Layout;
import { useNavigate, Link, useLocation, useParams } from 'react-router-dom';
import ThemeContext from '@/theme/ThemeContext';
import './index.css'
import { AuthContext } from '../../contexts/AuthContext';
import axios from 'axios';
import { useTranslation } from 'react-i18next';
import ReactECharts from 'echarts-for-react';
import MainLayout from '../../components/MainLayout'
const ProjectDetails = () => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const { theme, setTheme } = useContext(ThemeContext);
    const [userName, setUserName] = useState('');
    const { pkg_filename } = useParams();
    const location = useLocation();
    const { state } = location;
    const pkg_file_url = state?.pkg_file_url || '';
    const [projectInfo, setProjectInfo] = useState(null);
    const [loading, setLoading] = useState(true);
    const { token } = useContext(AuthContext);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [generating, setGenerating] = useState(false);
    const [loadingReport, setLoadingReport] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const checkLogin = () => {
        const storedToken = localStorage.getItem('enc_token');
        if (!storedToken) {
            message.warning(t('请先登录'));
            navigate('/login');
            return false;
        }
        return true;
    };

    const generateSBOM = () => {
        if (!pkg_file_url) {
            message.error(t('文件地址不可用'));
            return;
        }
        form.setFieldsValue({
            didid: projectInfo.didid,
            pkg_file_url: pkg_file_url //使用传递过来的值
        });
        showModal();
    };
    useEffect(() => {
        if (!checkLogin()) return;

        const storedUserName = localStorage.getItem('username');
        if (storedUserName) {
            setUserName(storedUserName);
        }

        if (!token || !pkg_filename) return;
        fetchProjectDetail();
    }, [token, pkg_filename]);
    const generateScan = async () => {
        try {
            setGenerating(true);
            const response = await axios.post('/api/v1/vulnerability/scan', {
                didid: projectInfo.didid,
                sbom_file_url: projectInfo.sbomFileUrl,
            }, {
                headers: {
                    'Authorization': token
                }
            });
            if (response.data.code === 0) {
                message.success(t('成功'));

                // 拼接完整URL并获取报告数据
                const fullReportUrl = `http://lanzomdata.asia${response.data.data.download_url}`;
                await fetchScanReport(fullReportUrl);
                setProjectInfo(prev => ({
                    ...prev,
                    scanReportFileUrl: fullReportUrl
                }));
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            } else {
                message.error(response.data.msg || t('扫描报告生成失败'));
            }
        } catch (error) {
            console.error('扫描错误:', error);
            message.error(error.response?.data?.msg || t('扫描报告生成失败'));
        } finally {
            setGenerating(false);
        }
    };
    const [scanData, setScanData] = useState(null);
    // 获取扫描报告数据
    const fetchScanReport = async (url) => {
        try {
            setLoadingReport(true);
            const response = await axios.get(url, {
                headers: { 'Authorization': token },
            });
            const rawData = response.data

            // 数据格式转换
            const formattedData = rawData.matches.map((item, index) => ({
                key: (index + 1).toString(),
                project: item.artifact.name,
                installed: item.artifact.version,
                fixedIn: item.vulnerability.fix.versions[0] || 'None',
                type: item.artifact.type || "UnknownPackage",
                vulnerability: item.vulnerability.id,
                severity: item.vulnerability.severity || 'Unknown',
            }));

            var _scanData = {
                matches: formattedData,
                db: rawData.descriptor.db.status,
                descriptor: {
                    name: rawData.descriptor.name || "",
                    timestamp: rawData.descriptor.timestamp || "",
                },
            };

            setScanData(_scanData);
        } catch (error) {
            console.error('获取报告失败:', error);
            message.error(t('获取扫描报告失败'));
        } finally {
            setLoadingReport(false);
        }
    };

    // 处理生成扫描报告
    const handleGenerateScan = async () => {
        try {
            setGenerating(true);
            const response = await axios.post('/api/v1/vulnerability/scan', {
                didid: projectInfo.didid,
                sbom_file_url: projectInfo.sbomFileUrl,
            }, { headers: { 'Authorization': token } });

            if (response.data.code === 0) {
                const fullUrl = `http://lanzomdata.asia${response.data.data.download_url}`;
                await fetchScanReport(fullUrl);
                message.success(t('成功'));
                window.location.reload();
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (error) {
            console.error('扫描错误:', error);
            message.error(error.response?.data?.msg || t('扫描失败'));
        } finally {
            setGenerating(false);
        }
    };

    // 漏洞严重性分布图表
    const renderSeverityChart = (scanData) => {
        if (!scanData?.matches?.length) {
            return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
        }

        // 统计严重性数量
        const severityCount = scanData.matches.reduce((acc, match) => {
            const severity = match.severity || 'Unknown'; // 确保字段正确
            acc[severity] = (acc[severity] || 0) + 1;
            return acc;
        }, {});

        // 定义颜色
        const getSeverityColor = (severity) => {
            const colors = {
                Critical: '#d63031',
                High: ' #e17055',
                Medium: ' #fdcb6e',
                Low: ' #00b894',
                Unknown: '#d9d9d9'
            };
            return colors[severity] || '#1890ff';
        };

        // ECharts 配置
        const option = {
            title: { text: t('漏洞严重性分布'), left: 'center' },
            tooltip: { trigger: 'item' },
            legend: { orient: 'vertical', left: 'left' },
            series: [
                {
                    name: '严重性',
                    type: 'pie',
                    radius: [20, 145],
                    roseType: 'area',
                    itemStyle: {
                        borderRadius: 5
                    },
                    data: Object.entries(severityCount).map(([name, value]) => ({
                        value,
                        name,
                        itemStyle: { color: getSeverityColor(name) }
                    })),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        return <ReactECharts option={option} style={{ height: '400px', marginBottom: '80px', marginTop: '60px' }} />;
    };

    // 漏洞类型统计图表
    const renderVulnerabilityTypes = () => {
        if (!scanData.matches?.length) return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;

        const typeCount = scanData.matches.reduce((acc, match) => {
            const type = match.type;
            acc[type] = (acc[type] || 0) + 1;
            return acc;
        }, {});

        const option = {
            title: { text: t('漏洞类型统计'), left: 'center' },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: 'category',
                data: Object.keys(typeCount),
                axisLabel: { rotate: 45 }
            },
            yAxis: { type: 'value' },
            series: [{
                data: Object.values(typeCount),
                type: 'bar',
                itemStyle: {
                    color: '#1890ff'
                }
            }]
        };

        return <ReactECharts option={option} style={{ height: 400 }} />;
    };

    // 获取严重性颜色
    const getSeverityColor = (severity) => {
        const colors = {
            Critical: '#f5222d',
            High: '#fa8c16',
            Medium: '#faad14',
            Low: '#52c41a',
            Unknown: '#d9d9d9'
        };
        return colors[severity] || colors.Unknown;
    };

    // 渲染扫描报告详情
    const renderReportDetails = () => {
        if (!scanData) return null;

        const tabItems = [
            {
                key: '1',
                label: t('漏洞概览'),
                children: (
                    <div>
                        <div style={{ display: 'flex', gap: 26, marginBottom: 24 }}>
                            <Card title={t("总漏洞数")}>
                                <h2>{scanData.matches.length || 0}</h2>
                            </Card>
                            <Card title={t("数据库版本")}>
                                <p>{scanData.db.schemaVersion}</p>
                            </Card>
                        </div>
                        {renderSeverityChart(scanData)}
                        {renderVulnerabilityTypes()}
                    </div>
                ),
            },
            {
                key: '2',
                label: t('漏洞列表'),
                children: (
                    <div>
                        {loadingReport ? (
                            <div style={{ textAlign: 'center', padding: '50px' }}>
                                <Spin size="large" tip={t("加载漏洞列表中...")} />
                            </div>
                        ) : scanData.matches.length ? (
                            <div style={{ width: '100%', overflow: 'hidden' }}>
                                <Collapse accordion style={{ width: '100%' }}>
                                    {scanData.matches
                                        .slice(
                                            (pagination.current - 1) * pagination.pageSize,
                                            pagination.current * pagination.pageSize
                                        )
                                        .map((match, index) => (
                                            <Collapse.Panel
                                                key={index}
                                                header={
                                                    <span style={{
                                                        display: 'inline-block',
                                                        maxWidth: '100%',
                                                        overflow: 'hidden',
                                                        textOverflow: 'ellipsis'
                                                    }}>
                                                        <Tag color={getSeverityColor(match.severity)}>
                                                            {t(match.severity || 'Unknown')}
                                                        </Tag>
                                                        {match.vulnerability.id}: {match.project}@{match.installed}
                                                    </span>
                                                }
                                            >
                                            </Collapse.Panel>
                                        ))
                                    }
                                </Collapse>
                                <Pagination
                                    style={{ marginTop: 10 }}
                                    current={pagination.current}
                                    pageSize={pagination.pageSize}
                                    total={scanData.matches.length}
                                    onChange={(page, pageSize) => setPagination({ ...pagination, current: page, pageSize })}
                                    showSizeChanger
                                    showQuickJumper
                                    showTotal={total => t('共 {{total}} 条漏洞', { total })}
                                />
                            </div>
                        ) : (
                            <Empty description={t("未发现漏洞")} />
                        )}
                    </div>
                ),
            },
            {
                key: '3',
                label: t('扫描信息'),
                children: (
                    <Descriptions bordered column={1}>
                        <Descriptions.Item label={t("扫描工具")}>
                            {scanData.descriptor?.name}
                        </Descriptions.Item>
                        <Descriptions.Item label={t("扫描时间")}>
                            {new Date(scanData.descriptor.timestamp).toLocaleString()}
                        </Descriptions.Item>
                        <Descriptions.Item label={t("数据源")}>
                            {scanData.db?.from}
                        </Descriptions.Item>
                    </Descriptions>
                ),
            },
        ];

        return <Tabs defaultActiveKey="1" items={tabItems} />;
    };
    // 在扫描报告Descriptions.Item中使用
    const renderScanReportSection = () => {
        if (loadingReport) {
            return (
                <Flex align="center" gap="small">
                    <Button type="primary" loading style={{ width: '100px' }}>
                        {t("加载中...")}
                    </Button>
                    <span>{t("正在加载扫描报告，请稍候...")}</span>
                </Flex>
            );
        }

        if (scanData) {
            return renderReportDetails();
        } else if (projectInfo?.scanReportFileUrl) {
            return (
                <Button
                    type="primary"
                    style={{ width: '200px' }}
                    onClick={() => fetchScanReport(`http://lanzomdata.asia${projectInfo.scanReportFileUrl}`)}
                    loading={loadingReport}
                >
                    {loadingReport ? t('加载中...') : t('加载扫描报告')}
                </Button>
            );
        } else {
            return (
                <div>
                    <p style={{ color: 'orange', marginBottom: 8 }}>
                        {t("当前项目尚未生成扫描报告")}
                    </p>
                    {projectInfo?.sbomFileUrl ? (
                        <Button
                            type="primary"
                            onClick={handleGenerateScan}
                        >
                            {generating ? t('生成中...') : t('生成扫描报告')}
                        </Button>
                    ) : (
                        <p>{t("请先生成SBOM文件")}</p>
                    )}
                </div>
            );
        }
    };

    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
        form.resetFields();
    };
    const handleGenerate = async () => {
        try {
            setGenerating(true);
            const values = await form.validateFields();

            const response = await axios.post('/api/v1/sbom/generate', {
                didid: projectInfo.didid,
                format: values.format,
                pkg_file_url: values.pkg_file_url
            }, {
                headers: {
                    'Authorization': token
                }
            });

            if (response.data.code === 0) {
                message.success(t('成功'));
                // 更新projectInfo状态
                setProjectInfo(prev => ({
                    ...prev,
                    sbomFileUrl: response.data.data.sbomFileUrl
                }));
                handleCancel();
                window.location.reload();
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (error) {
            message.error(error.response?.data?.msg || t('失败'));
        } finally {
            setGenerating(false);
        }
    };

    const fetchProjectDetail = async () => {
        try {
            if (!checkLogin()) return; // 每次API调用前检查登录状态

            if (!pkg_filename || typeof pkg_filename !== 'string') {
                message.warning(t('文件名无效'));
            }
            const response = await axios.post(
                '/api/v1/pkg/getDetail',
                { pkg_filename },
                {
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                }
            );
            if (response.data.code === 0) { setProjectInfo(response.data.data); }
            else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (error) {
            console.error("API 错误详情:", {
                response: error.response?.data
            });
            message.error(error.response?.data?.msg || t('失败'));
        } finally {
            setLoading(false);
        }
    };
    if (!localStorage.getItem('enc_token')) {
        return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <Card>
                    <p>{t('您需要登录才能访问此页面')}</p>
                    <Button type="primary" onClick={() => navigate('/login')}>
                        {t('前往登录')}
                    </Button>
                </Card>
            </div>
        );
    }
    return (
        <MainLayout defaultSelectedKey="3">
            <Card title={t("项目详情")} loading={loading}>
                {projectInfo && (
                    <Descriptions bordered column={1}>
                        <Descriptions.Item label={t("DID标识")}>
                            {projectInfo.didid}
                        </Descriptions.Item>

                        <Descriptions.Item label={t("SBOM文件")}>
                            {projectInfo.sbomFileUrl ? (
                                <div>
                                    <p>{t('SBOM文件已生成：')}</p>
                                    <p style={{
                                        backgroundColor: theme === 'dark' ? '#001529' : '#f0f0f0',
                                        padding: '8px',
                                        borderRadius: '4px',
                                        wordBreak: 'break-all',
                                        overflowWrap: 'break-word',
                                        whiteSpace: 'pre-wrap',
                                    }}>
                                        {projectInfo.sbomFileUrl}
                                    </p>
                                    <Button
                                        type="link"
                                        className='fuzhibutton'
                                        style={{ width: '100px' }}
                                        onClick={() => {
                                            navigator.clipboard.writeText(projectInfo.sbomFileUrl);
                                            message.success(t('已复制'));
                                        }}
                                    >
                                        {t('复制地址')}
                                    </Button>
                                </div>
                            ) : (
                                <div>
                                    <p style={{ color: 'orange', marginBottom: 8 }}>
                                        {t('当前项目尚未生成SBOM文件')}
                                    </p>
                                    <Button
                                        type="primary"
                                        className='sbom-button'
                                        onClick={generateSBOM}
                                    >
                                        {t("生成SBOM文件")}
                                    </Button>
                                </div>
                            )}
                        </Descriptions.Item>

                        {/* 扫描报告状态 */}
                        <Descriptions.Item label={t("生成扫描报告")}>
                            {projectInfo.scanReportFileUrl ? (
                                <div>
                                    <p>{t('扫描报告已生成：')}</p>
                                    <p style={{
                                        backgroundColor: theme === 'dark' ? '#001529' : '#f0f0f0',
                                        padding: '8px',
                                        borderRadius: '4px',
                                        wordBreak: 'break-all',
                                        overflowWrap: 'break-word',
                                        whiteSpace: 'pre-wrap',
                                    }}>
                                        {projectInfo.scanReportFileUrl}
                                    </p>
                                    <Button
                                        type="link"
                                        className='fuzhibutton'
                                        style={{ width: '100px' }}
                                        onClick={() => {
                                            navigator.clipboard.writeText(projectInfo.scanReportFileUrl);
                                            message.success(t('已复制'));
                                        }}
                                    >
                                        {t('复制地址')}
                                    </Button>
                                </div>
                            ) : (
                                <div>
                                    <p style={{ color: 'orange', marginBottom: 8 }}>
                                        {t('当前项目尚未生成扫描报告')}
                                    </p>
                                    {projectInfo.sbomFileUrl ? (
                                        <Button
                                            type="primary"
                                            onClick={generateScan}
                                            loading={generating}
                                            style={{ width: "180px" }}
                                        >
                                            {t("生成扫描报告")}
                                        </Button>
                                    ) : (
                                        <p> {t('请先生成SBOM文件')}</p>
                                    )}
                                </div>
                            )}
                        </Descriptions.Item>
                        <Descriptions.Item label={t("扫描报告")}>
                            {renderScanReportSection()}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Card>
            <Modal
                title={t("生成SBOM文件")}
                open={isModalOpen}
                onOk={handleGenerate}
                onCancel={handleCancel}
                confirmLoading={generating}
                okText={t("生成")}
                cancelText={t("取消")}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        format: 'spdx-json'
                    }}
                >
                    <Form.Item
                        label={t("DID标识")}
                        name="didid"
                    >
                        <Input disabled />
                    </Form.Item>

                    <Form.Item
                        label={t("文件存储地址")}
                        name="pkg_file_url"
                    >
                        <Input disabled placeholder={pkg_file_url || "加载中..."} />
                    </Form.Item>

                    <Form.Item
                        label={t("SBOM格式")} rules={[{ required: true, message: t('请选择SBOM格式') }]}
                        name="format"
                    >
                        <Radio.Group>
                            <Radio value="spdx-json">SPDX-JSON</Radio>
                            <Radio value="cdx-json">CDX-JSON</Radio>
                        </Radio.Group>
                    </Form.Item>
                </Form>
            </Modal>
        </MainLayout>
    );
};

export default ProjectDetails;